/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.myself;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.activity.delivery.UserAddressActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.global.DanluApplication;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.RegisterEditText;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.mydl.deliveraddr.AddDeliverAddressRequest;
import cn.com.hd.mall.web.webservices.entity.request.mydl.deliveraddr.AddDeliverAddressRequest.AddDeliverAddressModel;
import cn.com.hd.mall.web.webservices.entity.request.mydl.deliveraddr.GetTerminalAddressRequest;
import cn.com.hd.mall.web.webservices.entity.request.mydl.deliveraddr.ModifyDeliverAddressRequest;
import cn.com.hd.mall.web.webservices.entity.request.mydl.deliveraddr.ModifyDeliverAddressRequest.ModifyDeliverAddressModel;
import cn.com.hd.mall.web.webservices.entity.response.mydl.deliveraddr.GetTerminalAddressReponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;


/**
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-01-16 16:32<br/>
 *
 * <p>
 * 增加/修改收货地址画面
 * </p>
 */
public class MyReceiveAddressAddActivity extends BaseActivity implements OnClickListener {
    /**
     * 添加收货地址数据请求
     */
    AddDeliverAddressRequest addDeliverAddressRequest;
    /**
     * 修改收货地址数据请求
     */
    ModifyDeliverAddressRequest modifyDeliverAddressRequest;
    /**
     * 丹露用异步任务代理
     */
    // private DanluTaskProxy danluTaskProxy;
    /**
     * 画面Title
     */
    private TextView title;
    /** 收货人背景框 */
    /**
     * 收货人
     */
    private RegisterEditText consigneeName;
    /**
     * 收货人电话
     */
    private RegisterEditText consigneeTel;
    /**
     * 所在地区 布局
     */
    private RelativeLayout selectAddress;
    /**
     * 所在地区
     */
    private TextView consigneeCity;
    /**
     * 详细地址
     */
    private RegisterEditText consigneeDetailAdd;
    /**
     * 保存
     */
    private Button btnSure;
    /**
     * 收货人
     */
    private String name;
    /**
     * 联系电话
     */
    private String tel;
    /**
     * 详细地址
     */
    private String detailadd;
    /**
     * 收货地址id
     */
    private String addressId;
    /**
     * 校验输入 文字
     */
    private boolean flag = false;
    /**
     * 省份Code
     */
    private String provinceCode;
    /**
     * 城市Code
     */
    private String cityCode;
    /**
     * 区域Code
     */
    private String districtCode;
    private String isdefau;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //        getDelegate ().setContentView (R.layout.layout_add_my_address, R.add_my_address.class);
        setContentView(R.layout.activity_myreceive_address_add);

        initViews();
        setViews();
    }

    private void initViews() {
        title = (TextView) findViewById(R.id.title);
        consigneeName = (RegisterEditText) findViewById(R.id.consigneeName);
        consigneeTel = (RegisterEditText) findViewById(R.id.consigneeTel);
        selectAddress = (RelativeLayout) findViewById(R.id.selectAddress);
        consigneeCity = (TextView) findViewById(R.id.consigneeCity);
        consigneeDetailAdd = (RegisterEditText) findViewById(R.id.consigneeDetailAdd);
        btnSure = (Button) findViewById(R.id.btn_sure);
        consigneeDetailAdd = (RegisterEditText) findViewById(R.id.consigneeDetailAdd);
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    /**
     * 页面初始化
     */
    private void setViews() {
        // 判断跳转页面 ， 0 添加页面，1 编辑页面
        int i = getIntent().getIntExtra("RECEIVE", -1);

        if (i == 1) {
            // 显示编辑title
            title.setText(R.string.edit_receive_address_title);
            // 获取要编辑数据
            getEditData();

        } else {
            // 显示添加title
            title.setText(R.string.add_receive_address_title);
            //获取终端店所在地址
            GetTerminalAddressRequest getTerminalAddressRequest = new GetTerminalAddressRequest();
            getTerminalAddressRequest.setToken(agent.getToken());
            getTerminalAddressRequest.setTerminalCustomerId(agent.getRoleID());
            //add by llq
            agent.getApi().getStoreAddress(getTerminalAddressRequest).compose(OperatorUtils.<GetTerminalAddressReponse>defaultSchedulers())
                    .subscribe(new GeneralBusinessObserver<GetTerminalAddressReponse>(MyReceiveAddressAddActivity.this, true, R.string.loading_common_msg, false) {
                        @Override
                        protected void onSuccess(GetTerminalAddressReponse getTerminalAddressReponse) {
                            String address = getTerminalAddressReponse.getTerminalAreaProvinceValue() + getTerminalAddressReponse.getTerminalAreaCityValue() + getTerminalAddressReponse.getTerminalAreaDistrictValue();
                            consigneeCity.setText(address);
                            provinceCode = getTerminalAddressReponse.getTerminalAreaProvinceCode();
                            cityCode = getTerminalAddressReponse.getTerminalAreaCityCode();
                            districtCode = getTerminalAddressReponse.getTerminalAreaDistrictCode();
                        }
                    });
        }
        selectAddress.setOnClickListener(this);
        btnSure.setOnClickListener(this);
    }

    /**
     * 获取要编辑数据
     */
    private void getEditData() {
        if (getIntent() != null) {
            consigneeName.setText(getIntent().getStringExtra("PERSON"));
            consigneeTel.setText(getIntent().getStringExtra("MOBOL"));
            String address = getIntent().getStringExtra("PRIV") + getIntent().getStringExtra("CITY") + getIntent().getStringExtra("DIST");
            consigneeCity.setText(address);
            provinceCode = getIntent().getStringExtra("PRIVCO");
            cityCode = getIntent().getStringExtra("CITYCO");
            districtCode = getIntent().getStringExtra("DISTCO");
            consigneeDetailAdd.setText(getIntent().getStringExtra("DETAIL"));
            addressId = getIntent().getStringExtra("ADDID");
            isdefau = getIntent().getStringExtra("ISDEFAU");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sure:
                // 校验数据
                checkData();
                // 保存数据
                if (flag) {
                    String str = getResources().getString(R.string.edit_receive_address_title);
                    if (title.getText().equals(str)) {
                        // 保存修改数据
                        saveModifyData();
                    } else {
                        // 保存添加数据
                        saveAddData();
                    }
                }
                break;

            case R.id.selectAddress:
                // 隐藏软键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(selectAddress.getWindowToken(), 0); // 强制隐藏键盘
                // 跳转区域列表
                Intent intent = new Intent();
                intent.setClass(MyReceiveAddressAddActivity.this,
                        AddressListActivity.class);
                startActivityForResult(intent, 100);
                break;

            default:
                break;
        }
    }

    /**
     * 输入内容校验
     */
    private void checkData() {
        name = String.valueOf(consigneeName.getText());
        tel = String.valueOf(consigneeTel.getText());
        // 收货地址
        String city = String.valueOf(consigneeCity.getText());
        detailadd = String.valueOf(consigneeDetailAdd.getText());
        if (CommonUtils.isStringBlank(name)) {
            ToastUtil.getInstance().show(R.string.consignee_name_not_null);
            flag = false;
        } else if (!CommonUtils.isMobileNumber(tel)) {
            ToastUtil.getInstance().show(R.string.consignee_tel_not_right);
            flag = false;
        } else if (CommonUtils.isStringBlank(city)) {
            ToastUtil.getInstance().show(R.string.consignee_city_not_null);
            flag = false;
        } else if (CommonUtils.isStringBlank(detailadd)) {
            ToastUtil.getInstance().show(R.string.consignee_detail_add_not_null);
        } else {
            flag = true;
        }
    }

    /**
     * 保存修改数据
     */
    private void saveModifyData() {
        ModifyDeliverAddressModel modifyDeliverAddressModel = new ModifyDeliverAddressModel();
        modifyDeliverAddressModel.setDeliverPerson(name);
        modifyDeliverAddressModel.setDeliverMobile(tel);
        modifyDeliverAddressModel.setAreaProvinceCode(provinceCode);
        modifyDeliverAddressModel.setAreaCityCode(cityCode);
        modifyDeliverAddressModel.setAreaDistrictCode(districtCode);
        modifyDeliverAddressModel.setAddressDetail(detailadd);
        modifyDeliverAddressModel.setAddressId(addressId);
        modifyDeliverAddressRequest = new ModifyDeliverAddressRequest();
        // 设置参数：会话验证标识
        modifyDeliverAddressRequest.setToken(agent.getToken());
        modifyDeliverAddressRequest.setDeliverAddress(modifyDeliverAddressModel);
        // 修改收货地址
        agent.getApi().modifyDeliverAddress(modifyDeliverAddressRequest).compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(MyReceiveAddressAddActivity.this, true, R.string.tips_saving_modify_add, false) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        Intent intent = new Intent(MyReceiveAddressAddActivity.this, MyReceiveAddressActivity.class);
                        intent.putExtra("ADDRESID", addressId);
                        intent.putExtra("ISDEFAU", isdefau);
                        setResult(RESULT_OK, intent);
                        ToastUtil.getInstance().show(R.string.edit_sucess);
                        MyReceiveAddressAddActivity.this.finish();
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        String displayMsg = "";
                        switch (code) {
                            case "1":
                                approveDialog();
                                break;
                            case "2":
                                displayMsg = getString(R.string.add_shopping_cart_error_1);
                                break;
                            case "3":
                                Intent intent = new Intent(MyReceiveAddressAddActivity.this, MyReceiveAddressActivity.class);
                                setResult(RESULT_OK, intent);
                                MyReceiveAddressAddActivity.this.finish();
                                ToastUtil.getInstance().show(R.string.del_failed);
                                break;
                            default:
                                displayMsg = getString(R.string.edit_fail);
                                break;
                        }
                        return displayMsg;
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        if (!TextUtils.isEmpty(displayMessage)) {
                            ToastUtil.getInstance().show(displayMessage);
                        }
                    }
                });
    }

    /**
     * 保存添加数据
     */
    private void saveAddData() {
        AddDeliverAddressModel addDeliverAddressModel = new AddDeliverAddressModel();
        addDeliverAddressModel.setDeliverPerson(name);
        addDeliverAddressModel.setDeliverMobile(tel);
        addDeliverAddressModel.setAreaProvinceCode(provinceCode);
        addDeliverAddressModel.setAreaCityCode(cityCode);
        addDeliverAddressModel.setAreaDistrictCode(districtCode);
        addDeliverAddressModel.setAddressDetail(detailadd);
        addDeliverAddressModel.setIsDefault("1");
        addDeliverAddressRequest = new AddDeliverAddressRequest();
        // 设置参数：会话验证标识
        addDeliverAddressRequest.setToken(agent.getToken());
        addDeliverAddressRequest.setDeliverAddress(addDeliverAddressModel);
        // 增加收货地址
        agent.getApi().addDeliverAddress(addDeliverAddressRequest).compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(MyReceiveAddressAddActivity.this, true, R.string.tips_saving_add_address, false) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        if (getIntent().getStringExtra("ORDERADD") != null) {
                            Intent intent = new Intent(MyReceiveAddressAddActivity.this, UserAddressActivity.class);
                            setResult(200, intent);
                        } else {
                            Intent intent = new Intent(MyReceiveAddressAddActivity.this, MyReceiveAddressActivity.class);
                            setResult(RESULT_OK, intent);
                        }
                        ToastUtil.getInstance().show(R.string.add_sucess);
                        finish();
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        String displayMsg = "";
                        if (code.equals("1")){
                            approveDialog();
                        } else {
                            displayMsg = DanluApplication.get().getString(R.string.receive_address_add_error);
                        }
                        return displayMsg;
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        if (!TextUtils.isEmpty(displayMessage)) {
                            ToastUtil.getInstance().show(getString(R.string.add_fail) + ":" + displayMessage);
                        }
                    }
                });

        //        if (getDelegate().getTaskQueueHandler().get(this) != null) {
        // 重启任务
        //            getDelegate().getTaskQueueHandler().get(this).restart();

        //            danluTaskProxy.addDeliverAddress(addDeliverAddressRequest, onAddDeliverAddressListener);
        //        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 100:
                consigneeCity.setText(data.getStringExtra("ADDR"));
                provinceCode = data.getStringExtra("PCODE");
                cityCode = data.getStringExtra("CCODE");
                districtCode = data.getStringExtra("DCODE");
                break;

            default:
                break;
        }
    }

    /**
     * 待审批对话框
     */
    private void approveDialog() {
//        ViewDialog.Builder builder = new ViewDialog.Builder(delegate.getContext());
        ViewDialog.Builder builder = new ViewDialog.Builder(MyReceiveAddressAddActivity.this);
        // 设置标题
        builder.setTitle(R.string.receive_address_add_successs);
        // 设置信息
        builder.setMessage(getString(R.string.receive_address_approve_msg));
        // 设置Positive按钮点击监听
        builder.setPositiveButton(R.string.receive_address_approve_ok,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 对话框关闭
                        dialog.dismiss();
                        MyReceiveAddressAddActivity.this.finish();
                    }
                });
        // 创建对话框并显示
        builder.create().show();
    }
}